package javathread;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import command.protobuf.MessageBufProtoBuf.RpcMessage;

import javathread.MultThreadSocketTest.ReadThread;
import javathread.MultThreadSocketTest.SingleThreadRWServer;

public class MultiThreadClient {
	public static int port = 10111;

	public static class TestThread extends Thread {
		@Override
		public void run() {
			try {
				Socket sock;
				sock = new Socket(InetAddress.getByName("127.0.0.1"), port);
				sock.setTcpNoDelay(true);
				DataOutputStream output = new DataOutputStream(
						new BufferedOutputStream(sock.getOutputStream()));
				// new ReadThread(sock).start();
				int count = 30;
				ByteArrayOutputStream ao = new ByteArrayOutputStream();
				DataOutputStream buf = new DataOutputStream(ao);
				RpcMessage.Header header = RpcMessage.Header.newBuilder()
						.setID(0).setCmdType(0).setFlag(0).build();
				header.writeTo(buf);
				byte[] arr = ao.toByteArray();
				System.out.println(arr.length);
				output.writeInt(arr.length);
				output.write(ao.toByteArray());
				//output.write(new byte[]{1,1,1,1,1,1});
				output.flush();

				DataInputStream input = new DataInputStream(
						new BufferedInputStream(sock.getInputStream()));
				RpcMessage.Header ret = RpcMessage.Header.parseFrom(input);
				System.out.println("server echos " + ret);

				Thread.sleep(1000);
				sock.close();
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	public static void main(String[] args) throws IOException,
			InterruptedException {
		new TestThread().start();
		Thread.sleep(1000);
	}
}
